const express = require('express');
const {
  readFileSync
} = require('fs');
const {
  resolve
} = require('path');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser.json());

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-methods', 'POST,GET');
  next();
});

app.get('/getCourses', function (req, res) {
  const field = req.query.field; //all/0/1/2/3

  let courseDatas = JSON.parse(readFileSync(resolve(__dirname, './data/courseDatas.json'), 'utf8'));

  if (field !== 'all') {
    courseDatas = courseDatas.filter((item) => {
      return item.field === field;
    });
  }

  const ret = {
    ret_code: 0,
    result: courseDatas
  }

  res.send(ret);
});

app.get('/getCourseFields', function (req, res) {
  const courseFields = JSON.parse(readFileSync(resolve(__dirname, './data/courseField.json'), 'utf8'));

  const ret = {
    ret_code: 0,
    result: courseFields
  }

  res.send(ret);
});

app.get('/getCourseDatas', function (req, res) {

  const field = req.query.field;
  let ret;

  const courseDatas = JSON.parse(readFileSync(resolve(__dirname, './data/courseDatas.json'), 'utf8'));
  const courseSwiper = JSON.parse(readFileSync(resolve(__dirname, './data/swiper.json'), 'utf8'));
  const courseFields = JSON.parse(readFileSync(resolve(__dirname, './data/courseField.json'), 'utf8'));
  const courseRecom = JSON.parse(readFileSync(resolve(__dirname, './data/recomCourse.json'), 'utf8'));

  if (field === 'all') {
    ret = {
      ret_code: 0,
      result: {
        swipers: courseSwiper,
        fields: courseFields,
        courses: courseDatas,
        recomCourses: courseRecom
      }
    }

    res.send(ret);
  } else {
    res.send('can not find field');
  }

  
});



app.listen(8080, function () {
  console.log('Server has been started on 8080!');
});